package io.github.frailty9.crserver.controller

import cn.dev33.satoken.annotation.SaCheckRole
import cn.dev33.satoken.stp.StpUtil
import cn.dev33.satoken.util.SaResult
import io.github.frailty9.crserver.dso.service.UserService
import io.github.frailty9.crserver.model.User
import org.noear.solon.annotation.Controller
import org.noear.solon.annotation.Inject
import org.noear.solon.annotation.Mapping
import org.noear.solon.annotation.Path
import org.noear.solon.web.cors.annotation.CrossOrigin

@Suppress("unused")
@CrossOrigin(origins = "*")
@Controller
@Mapping("/api/user")
class UserController {

    @Inject
    private lateinit var userService: UserService

    @Mapping("/info")
    fun info(): SaResult {
        val uid = StpUtil.getLoginIdAsLong()
        val userInfo = userService.getInfo(uid)
        return SaResult.data(userInfo)
    }

    @Mapping("/info/{id}")
    @SaCheckRole("admin")
    fun getInfo(@Path id: Long): SaResult? {
        return SaResult.data(userService.getInfo(id))
    }

    @Mapping("/update")
    fun update(user: User): SaResult {
        if (StpUtil.getRoleList().contains("sys_admin")) {
            if (user.id == null) {
                return SaResult.error("未指定修改的用户ID")
            }
        } else {
            val uid = StpUtil.getLoginIdAsLong()
            if (user.id != null && user.id != uid) {
                return SaResult.error("无权修改其他用户信息")
            } else {
                user.id = uid
            }
        }
        userService.update(user)
        return SaResult.ok()
    }
}
